<template>
    <div class="chat-container">
        <!-- 左侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <i class="el-icon-user-solid"></i>
                    <span>专家服务平台</span>
                </div>
            </div>
            <div class="sidebar-content">
                <div class="session-filter">
                    <!-- <el-input placeholder="搜索用户..." prefix-icon="el-icon-search" size="small" class="search-input"></el-input> -->
                </div>
                <div class="session-list">
                    <div v-for="session in sessions" :key="session.userId"
                        :class="['session-card', session.userId === currentUserId ? 'active' : '']"
                        @click="selectSession(session)">
                        <div class="session-avatar">
                            <el-avatar :src="session.user && session.user.avatar ? getImageUrl(session.user.avatar) : ''"
                                icon="el-icon-user-solid"></el-avatar>
                            <div class="online-status" v-if="session.user && session.user.online">在线</div>
                        </div>
                        <div class="session-info">
                            <div class="session-name">{{ session.user && session.user.name }}</div>
                            <div class="session-email">{{ session.user && session.user.email }}</div>
                            <div class="session-preview" v-if="getLastMessage(session.userId)">
                                <span class="preview-text">{{ getLastMessage(session.userId).content }}</span>
                                <span class="preview-time">{{ formatTime(getLastMessage(session.userId).sendTime) }}</span>
                            </div>
                        </div>
                        <div class="session-badge" v-if="getUnreadCount(session.userId)">{{ getUnreadCount(session.userId) }}</div>
                    </div>
                    <el-empty v-if="!sessions.length" description="暂无会话" class="empty-sessions"></el-empty>
                </div>
            </div>
            <div class="sidebar-footer">
                <div class="expert-profile">
                    <el-avatar :src="expertInfo.avatar ? getImageUrl(expertInfo.avatar) : ''" icon="el-icon-user-solid"></el-avatar>
                    <div class="expert-info">
                        <div class="expert-name">{{ expertInfo.name || '专家' }}</div>
                        <div class="expert-status">在线</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="chat-main">
            <div v-if="currentUserId" class="chat-content">
                <div class="chat-header">
                    <div class="header-info">
                        <div class="header-avatar">
                            <el-avatar :src="currentSession.user && currentSession.user.avatar ? getImageUrl(currentSession.user.avatar) : ''" icon="el-icon-user-solid"></el-avatar>
                        </div>
                        <div class="header-text">
                            <div class="header-name">{{ currentSession.user && currentSession.user.name }}</div>
                            <div class="header-email">{{ currentSession.user && currentSession.user.email }}</div>
                        </div>
                    </div>
                    <div class="header-actions">
                        <el-tooltip content="查看用户资料" placement="bottom">
                            <el-button icon="el-icon-user" circle size="small"></el-button>
                        </el-tooltip>
                        <el-tooltip content="刷新消息" placement="bottom">
                            <el-button icon="el-icon-refresh" circle size="small" @click="refreshMessages"></el-button>
                        </el-tooltip>
                    </div>
                </div>

                <div class="message-container" ref="msgBox">
                    <div class="chat-date">
                        <span>今天</span>
                    </div>
                    <div v-for="msg in messages" :key="msg.id" :class="['message-wrapper', msg.fromExpert ? 'expert' : 'user']">
                        <div class="message-avatar" v-if="!msg.fromExpert">
                            <el-avatar 
                                :src="currentSession.user && getImageUrl(currentSession.user.avatar)"
                                size="small" icon="el-icon-user-solid"></el-avatar>
                        </div>
                        <div class="message-body">
                            <div class="message-sender" v-if="!msg.fromExpert">{{ currentSession.user && currentSession.user.name }}</div>
                            <div class="message-bubble">
                                {{ msg.content }}
                            </div>
                            <div class="message-time">{{ formatTime(msg.sendTime) }}</div>
                        </div>
                        <div class="message-avatar" v-if="msg.fromExpert">
                            <el-avatar :src="getImageUrl(expertInfo.avatar)" size="small" icon="el-icon-user-solid"></el-avatar>
                        </div>
                    </div>
                </div>

                <div class="chat-footer">
                    <div class="message-input-wrapper">
                        <div class="message-tools">
                            <el-tooltip content="表情" placement="top">
                                <i class="el-icon-star-off tool-icon"></i>
                            </el-tooltip>
                            <el-tooltip content="图片" placement="top">
                                <i class="el-icon-picture-outline tool-icon"></i>
                            </el-tooltip>
                            <el-tooltip content="文件" placement="top">
                                <i class="el-icon-document tool-icon"></i>
                            </el-tooltip>
                            <el-tooltip content="快速回复" placement="top">
                                <i class="el-icon-chat-line-square tool-icon"></i>
                            </el-tooltip>
                        </div>
                        <div class="message-input">
                            <el-input 
                                v-model="input" 
                                type="textarea" 
                                :rows="2" 
                                placeholder="输入专业回复..." 
                                resize="none"
                                @keyup.enter.native.ctrl="send">
                            </el-input>
                        </div>
                        <div class="message-send">
                            <el-button type="primary" @click="send" :disabled="!input.trim()" icon="el-icon-position" circle></el-button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div v-else class="empty-chat">
                <div class="empty-chat-content">
                    <i class="el-icon-message"></i>
                    <p>选择一个用户开始咨询</p>
                    <div class="empty-chat-tips">
                        <div class="tip-item">
                            <i class="el-icon-info"></i>
                            <span>左侧可查看所有咨询用户</span>
                        </div>
                        <div class="tip-item">
                            <i class="el-icon-bell"></i>
                            <span>有新消息时会收到通知</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { getExpertSessions, getHistory } from '../api/ChatController';
import { sendChatMessage, connectChatSocket, closeChatSocket } from '../api/chatSocket';
import { getExpertDetail } from '../api/ExpertController';
export default {
    data() {
        return {
            expertInfo: {},
            sessions: [],
            currentUserId: null,
            currentSession: {},
            messagesMap: {}, // { userId: [msg, ...] }
            unreadMap: {}, // { userId: count }
            input: '',
            isTyping: false
        };
    },
    methods: {
        async loadSessions() {
            const res = await getExpertSessions(this.expertInfo.id);
            this.sessions = Array.isArray(res) ? res : (res.data || []);
            if (this.sessions.length) {
                this.selectSession(this.sessions[0]);
            }
        },
        handleSocketMessage(msg) {
            console.log('专家端收到消息', msg, this.expertInfo.id);
            if (!msg || msg.expertId != this.expertInfo.id) return; // 用 == 或都转字符串
            // 假设你用 messagesMap 存储每个会话的消息
            const userId = msg.userId;
            if (!this.messagesMap) this.messagesMap = {};
            if (!this.messagesMap[userId]) this.$set(this.messagesMap, userId, []);
            this.messagesMap[userId].push(msg);
            
            // 更新未读消息计数
            if (this.currentUserId !== userId) {
                if (!this.unreadMap[userId]) this.$set(this.unreadMap, userId, 0);
                this.$set(this.unreadMap, userId, this.unreadMap[userId] + 1);
            } else {
                this.$nextTick(this.scrollToBottom);
            }
        },
        async selectSession(session) {
            this.currentUserId = session.userId;
            this.currentSession = session;
            // 拉取历史消息
            const res = await getHistory({ userId: session.userId, expertId: this.expertInfo.id });
            this.$set(this.messagesMap, session.userId, Array.isArray(res) ? res : (res.data || []));
            // 清除未读计数
            this.$set(this.unreadMap, session.userId, 0);
            this.$nextTick(this.scrollToBottom);
        },
        send() {
            if (!this.input.trim()) return;
            const msg = {
                expertId: this.expertInfo.id,
                userId: this.currentUserId,
                content: this.input.trim(),
                fromExpert: true,
                sendTime: new Date().toISOString()
            };
            sendChatMessage(msg);
            this.input = '';
            this.$nextTick(this.scrollToBottom);
        },
        scrollToBottom() {
            const box = this.$refs.msgBox;
            if (box) box.scrollTop = box.scrollHeight;
        },
        getImageUrl(url) {
            if (!url) return '';
            return url.startsWith('/api') ? url : `/api${url}`;
        },
        formatTime(time) {
            if (!time) return '';
            if (typeof time === 'string') {
                // 兼容 ISO 字符串和 yyyy-MM-dd HH:mm:ss
                if (time.includes('T')) {
                    return time.replace('T', ' ').substring(11, 16); // 只显示时:分
                }
                return time.substring(11, 16); // 只显示时:分
            }
            if (typeof time === 'number') {
                // 毫秒时间戳
                const date = new Date(time);
                const pad = n => n < 10 ? '0' + n : n;
                return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
            }
            if (time instanceof Date) {
                const pad = n => n < 10 ? '0' + n : n;
                return `${pad(time.getHours())}:${pad(time.getMinutes())}`;
            }
            return String(time);
        },
        getLastMessage(userId) {
            const messages = this.messagesMap[userId] || [];
            return messages.length ? messages[messages.length - 1] : null;
        },
        getUnreadCount(userId) {
            return this.unreadMap[userId] || 0;
        },
        refreshMessages() {
            if (this.currentUserId) {
                this.selectSession(this.currentSession);
            }
        }
    },
    async mounted() {
        this.expertInfo = JSON.parse(localStorage.getItem('backUser') || '{}');
        console.log('专家端建立 WebSocket 连接', this.expertInfo.id);
        const data = await getExpertDetail(this.expertInfo.id); // 通过 userId 查专家表
        this.expertInfo.avatar = data.expert.avatar;
        this.expertInfo.name = data.expert.name;
        console.log(this.expertInfo);
        this.loadSessions();
        connectChatSocket({
            expertId: this.expertInfo.id, // 这里必须是专家表 userId
            userId: this.expertInfo.id,   // 这里也必须是专家表 userId
            role: 'expert',
            onMessage: this.handleSocketMessage.bind(this)
        });
    },
    computed: {
        messages() {
            return this.messagesMap[this.currentUserId] || [];
        }
    },
    beforeDestroy() {
        closeChatSocket();
    }
};
</script>
<style scoped>
.chat-container {
    display: flex;
    height: calc(100vh - 120px);
    min-height: 600px;
    margin: 20px auto;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
    background: #fff;
    max-width: 1200px;
}

/* 侧边栏样式 */
.sidebar {
    width: 320px;
    background: #34495e;
    display: flex;
    flex-direction: column;
}

.sidebar-header {
    padding: 24px;
    background: #2c3e50;
}

.logo {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    color: #ffffff;
}

.logo i {
    font-size: 24px;
    margin-right: 12px;
    color: #3498db;
}

.sidebar-content {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
}

.session-filter {
    padding: 16px;
}

.search-input :deep(.el-input__inner) {
    border-radius: 20px;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: #fff;
}

.search-input :deep(.el-input__prefix) {
    color: rgba(255, 255, 255, 0.7);
}

.session-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 10px 10px;
}

.session-card {
    position: relative;
    display: flex;
    padding: 16px;
    border-radius: 12px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.2s ease;
    background: rgba(255, 255, 255, 0.05);
}

.session-card:hover {
    background: rgba(255, 255, 255, 0.1);
}

.session-card.active {
    background: rgba(52, 152, 219, 0.2);
    border-left: 4px solid #3498db;
}

.session-avatar {
    position: relative;
    margin-right: 15px;
}

.online-status {
    position: absolute;
    bottom: -5px;
    right: -5px;
    padding: 2px 6px;
    background: #3498db;
    border-radius: 10px;
    font-size: 10px;
    color: white;
}

.session-info {
    flex: 1;
    min-width: 0;
    color: #fff;
}

.session-name {
    font-weight: 600;
    font-size: 16px;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.session-email {
    font-size: 13px;
    color: #3498db;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.session-preview {
    font-size: 13px;
    color: rgba(255, 255, 255, 0.6);
    display: flex;
    justify-content: space-between;
}

.preview-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 70%;
}

.preview-time {
    font-size: 11px;
    color: rgba(255, 255, 255, 0.4);
}

.session-badge {
    position: absolute;
    top: 12px;
    right: 12px;
    min-width: 20px;
    height: 20px;
    background: #e74c3c;
    color: white;
    border-radius: 10px;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 6px;
}

.sidebar-footer {
    padding: 16px;
    background: rgba(0, 0, 0, 0.1);
}

.expert-profile {
    display: flex;
    align-items: center;
}

.expert-info {
    margin-left: 12px;
    color: #fff;
}

.expert-name {
    font-weight: 600;
    font-size: 15px;
}

.expert-status {
    font-size: 13px;
    color: #3498db;
}

.empty-sessions {
    margin-top: 50px;
    color: rgba(255, 255, 255, 0.5);
}

/* 聊天区域样式 */
.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #f5f7fa;
}

.chat-content {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-info {
    display: flex;
    align-items: center;
}

.header-avatar {
    margin-right: 15px;
}

.header-text {
    display: flex;
    flex-direction: column;
}

.header-name {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
}

.header-email {
    font-size: 14px;
    color: #3498db;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.message-container {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    background: #f5f7fa;
}

.chat-date {
    text-align: center;
    margin: 20px 0;
    position: relative;
}

.chat-date::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    width: 100%;
    height: 1px;
    background: #e0e6ed;
    z-index: 1;
}

.chat-date span {
    background: #f5f7fa;
    padding: 0 15px;
    position: relative;
    z-index: 2;
    color: #8492a6;
    font-size: 14px;
    font-weight: 500;
}

.message-wrapper {
    display: flex;
    margin-bottom: 24px;
    align-items: flex-start;
}

.message-wrapper.expert {
    flex-direction: row-reverse;
}

.message-avatar {
    margin: 0 12px;
    align-self: flex-start;
}

.message-body {
    max-width: 70%;
}

.message-sender {
    font-size: 13px;
    color: #8492a6;
    margin-bottom: 4px;
}

.message-bubble {
    padding: 12px 18px;
    border-radius: 18px;
    position: relative;
    word-break: break-word;
    line-height: 1.6;
    font-size: 15px;
}

.message-wrapper.user .message-bubble {
    background: #fff;
    color: #2c3e50;
    border-bottom-left-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.message-wrapper.expert .message-bubble {
    background: #3498db;
    color: white;
    border-bottom-right-radius: 4px;
    text-align: right;
}

.message-time {
    font-size: 12px;
    color: #8492a6;
    margin-top: 6px;
    text-align: right;
}

.chat-footer {
    padding: 16px 24px;
    background: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.message-input-wrapper {
    display: flex;
    align-items: center;
    background: #f5f7fa;
    border-radius: 24px;
    padding: 8px 16px;
}

.message-tools {
    display: flex;
    margin-right: 10px;
}

.tool-icon {
    font-size: 20px;
    color: #8492a6;
    margin-right: 12px;
    cursor: pointer;
    transition: color 0.3s;
}

.tool-icon:hover {
    color: #3498db;
}

.message-input {
    flex: 1;
}

.message-input :deep(.el-textarea__inner) {
    border: none;
    background: transparent;
    padding: 8px 0;
    font-size: 15px;
    resize: none;
    height: auto;
    line-height: 1.6;
}

.message-input :deep(.el-textarea__inner:focus) {
    box-shadow: none;
}

.message-send {
    margin-left: 12px;
}

.message-send .el-button {
    background: #3498db;
    border-color: #3498db;
}

.message-send .el-button:hover, 
.message-send .el-button:focus {
    background: #2980b9;
    border-color: #2980b9;
}

.empty-chat {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

.empty-chat-content {
    text-align: center;
    color: #8492a6;
}

.empty-chat-content i {
    font-size: 64px;
    margin-bottom: 24px;
    color: #d3dce6;
}

.empty-chat-content p {
    font-size: 18px;
    margin-bottom: 24px;
    color: #5e6d82;
}

.empty-chat-tips {
    max-width: 300px;
    margin: 0 auto;
}

.tip-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.tip-item i {
    font-size: 16px;
    color: #3498db;
    margin-right: 10px;
    margin-bottom: 0;
}

@media (max-width: 768px) {
    .chat-container {
        flex-direction: column;
        height: calc(100vh - 80px);
        margin: 10px;
        border-radius: 12px;
    }
    
    .sidebar {
        width: 100%;
        height: 300px;
    }
    
    .chat-main {
        height: calc(100% - 300px);
    }
    
    .sidebar-footer {
        display: none;
    }
}
</style>